<template>
    <div>
        <h1 style="text-align: left;">员工薪资结构</h1><br>
        
        <el-form :model="formData" ref="form" :rules="rules" label-width="80px" :inline="true" style="display: flex; flex-direction: column; gap: 16px; text-align: left;">
            
            <el-form-item label="">
                
                <el-row :gutter="20" style="width: 100%;">
                    <el-col :span="12" :offset="0">
                        <span>员工姓名</span>
                        <el-select 
                            v-model="selectedEmp"
                            @change="handleEmpNameChange"
                            placeholder="请选择员工姓名"
                            clearable
                        >
                            <el-option 
                                v-for="emp in employeeList" 
                                :label="emp.employeeName" 
                                :value="emp.employeeId"
                            ></el-option>
                        </el-select>
                        <span>岗位</span>
                        <el-input v-model="formData.postsName" readonly></el-input>
                        <span>岗位工资（元）</span>
                        <el-input v-model="formData.baseSalary"></el-input>
                        <span>补贴（元）</span>
                        <el-input v-model="formData.subsidy"></el-input>
                    </el-col>
                    <el-col :span="12" :offset="0">
                        <span>所在部门</span >
                        <el-input v-model="formData.departmental" readonly></el-input>
                        <span>状态<br></br></span>
                         <el-radio-group v-model="formData.state">
                        <el-radio label="有效" value="有效">有效</el-radio>
                        <el-radio label="无效" value="无效">无效</el-radio>
                        </el-radio-group>
                        <span><br></br>绩效薪资（元）</span>
                        <el-input v-model="formData.paySalary"></el-input>
                        <span><br></br>基本工资（元）</span>
                        <el-input v-model="formData.baSa"></el-input>
                    </el-col>                       
                </el-row>                               
            </el-form-item>
            <el-form-item  style="margin-top: auto; align-self: flex-start;">
                <el-button type="primary" @click="onSubmit">提交</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref, defineEmits, onMounted } from 'vue';
import request from '@/api/request.js';
import { ElMessage } from 'element-plus';

let emits = defineEmits(['ref-table']);

let formData = ref({});
let employeeList = ref([]);
let selectedEmp = ref({});

// 页面加载时获取所有员工信息
onMounted(() => {
    find();
});

const handleEmpNameChange = (value) => {
    console.log('选中的员工ID:', value);
    if (value) {
        loadData();
    } else {
        formData.value = {};
    }
};

// 查询员工数据并填充表单
let loadData = () => {
    const temp = employeeList.value.find(item => item.employeeId == selectedEmp.value);
    console.log(temp);
    // 从选中的员工对象中获取所需ID
    const employeeId = temp.employeeId;
    const employeeName = temp.employeeName;
    const positionId = temp.entryPosition;  // 岗位ID
    const departmentId = temp.onboardingDepartment;  // 部门ID
    const basa = temp.officialSalary;
    console.log('获取到的原始ID数据:', {
        employeeId,
        positionId,
        departmentId,
        positionIdType: typeof positionId,
        departmentIdType: typeof departmentId
    });

    // 1. 查询岗位名称
    request({
        url: '/system/permission/post/finds',
        method: 'get',
        params: { postId: positionId }
    }).then(postRes => {
        console.log('岗位接口完整响应:', postRes);
        console.log('岗位接口返回数据:', postRes.data);
        
        // 显示原始响应结构，帮助确定正确的字段名
        if (postRes.data && postRes.data.length > 0) {
            console.log('岗位第一条数据结构:', postRes.data[0]);
        }
        
        // 尝试多种可能的字段名获取岗位名称
        let postsName = '未知岗位';
        if (postRes.data && postRes.data.length > 0) {
            const postData = postRes.data[0];
            // 尝试常见的字段名
            postsName = postData.postName || postData.name || postData.positionName || positionId;
        }
        console.log('解析后的岗位名称:', postsName);

        // 2. 查询部门名称
        return request({
            url: '/department/finds',
            method: 'get',
            params: { deptId: departmentId }
        }).then(deptRes => {
            console.log('部门接口完整响应:', deptRes);
            console.log('部门接口返回数据:', deptRes.data);
            
            // 显示原始响应结构，帮助确定正确的字段名
            if (deptRes.data && deptRes.data.length > 0) {
                console.log('部门第一条数据结构:', deptRes.data[0]);
            }
            
            // 尝试多种可能的字段名获取部门名称
            let departmentName = '未知部门';
            if (deptRes.data && deptRes.data.length > 0) {
                const deptData = deptRes.data[0];
                // 尝试常见的字段名
                departmentName = deptData.deptName || deptData.name || deptData.departmentName || departmentId;
            }
            console.log('解析后的部门名称:', departmentName);

            // 3. 查询薪资信息
            return request({
                url: '/salary/setup/disposition/find',
                method: 'get',
                params: {
                    postsName: postsName,
                    departmental: departmentName
                    
                }
            }).then(salaryRes => {
                // 填充表单数据
                formData.value = {
                    empId: employeeId,
                    emp: employeeName,
                    baSa: basa,
                    postsName: postsName,  // 显示解析后的岗位名称
                    departmental: departmentName,  // 显示解析后的部门名称
                    // 薪资相关字段...
                };
                
                // 如果有薪资数据，补充完整
                if (salaryRes.data && salaryRes.data.length > 0) {
                    const aip = salaryRes.data[0];
                    const subsidy = aip.bonus + aip.seniorityWages + 
                                   aip.transportationSubsidy + aip.housingAllowance + 
                                   aip.mealSubsidy + aip.otherSubsidies;
                    
                    formData.value.baseSalary = aip.baseSalary || '';
                    formData.value.subsidy = subsidy || '';
                    formData.value.state = aip.state || '有效';
                    formData.value.paySalary = aip.paySalary || '';
                }
            });
        });
    }).catch(error => {
        console.error('查询信息失败:', error);
    });
};

const onSubmit = async () => {
    const temp = employeeList.value.find(item => item.employeeId == selectedEmp.value);
    // 验证是否选择了员工
    if (!selectedEmp.value) {
        ElMessage.warning('请先选择员工');
        return;
    }

    try {
        // 先查询该员工是否已有数据
        const checkRes = await request({
            url: '/salary/setup/empdisposition/ba',
            method: 'get',
            params: {
                emp: temp.employeeId  // 将员工ID传入查询接口
            }
        });

        // 检查是否已有数据（根据实际接口返回格式调整判断条件）
        if (checkRes.data && (checkRes.data.length > 0 || Object.keys(checkRes.data).length > 0)) {
            ElMessage.warning('该员工的薪资结构数据已存在');
            return;
        }

        // 没有数据则执行添加操作
        const submitData = {
            ...formData.value,
            emp: selectedEmp.value
        };
        
        const res = await request({
            url: '/salary/setup/empdisposition/empdisposition',
            method: 'post',
            data: submitData
        });

        ElMessage.success('提交成功');
        emits('ref-table');
        // 重置表单
        formData.value = {};
        selectedEmp.value = '';
    } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('操作失败，请重试');
    }
};

// 获取所有员工信息
let find = () => {
    request({
        url: '/emp',
        method: 'get'
    }).then(res => {
        if (res.data) {
            employeeList.value = res.data;
        }
    }).catch(error => {
        console.error('获取员工列表失败:', error);
    });
};
</script>

<style scoped>

</style>
    